package com.samfdl.socket;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {
    private Button btnConnect, btnDisconnect, btnSend;
    private TextView Receive;
    private EditText mEdit;

    private Socket socket;
    private ExecutorService mThreadPool;

    private BufferedReader bufferedReader;
    private OutputStream outputStream;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化所有按钮
        btnConnect = findViewById(R.id.connect);
        btnDisconnect = findViewById(R.id.disconnect);
        btnSend = findViewById(R.id.send);
        mEdit = findViewById(R.id.edit);
        Receive = findViewById(R.id.Receive);

        // 初始化线程池
        mThreadPool = Executors.newCachedThreadPool();

        btnConnect.setOnClickListener(v -> {
            // 利用线程池直接开启一个线程 & 执行该线程
            mThreadPool.execute(() -> {
                try {
                    // 创建Socket对象 & 指定服务端的IP 及 端口号
                    socket = new Socket("192.168.68.100", 45450);

                    // 判断客户端和服务器是否连接成功
                    System.out.println("socket.isConnected(): " + socket.isConnected());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        });

        /**
         * 接收 服务器消息
         */
        Receive.setOnClickListener(v -> {
            // 利用线程池直接开启一个线程 & 执行该线程
            mThreadPool.execute(() -> {
                try {
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    System.out.println("socket.response: " + bufferedReader.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        });

        btnSend.setOnClickListener(v -> mThreadPool.execute(() -> {
            try {
                outputStream = socket.getOutputStream();
                outputStream.write((mEdit.getText().toString() + "\n").getBytes("utf-8"));
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }));

        btnDisconnect.setOnClickListener(v -> {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (socket != null) {
                    socket.close();
                }
                System.out.println("socket.isConnected(): " + socket.isConnected());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            System.out.println("=================");
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String IPAddress = intToIp(wifiInfo.getIpAddress());
        System.out.println("IPAddress-->>" + IPAddress);

        DhcpInfo dhcpinfo = wifiManager.getDhcpInfo();
        String serverAddress = intToIp(dhcpinfo.serverAddress);
        System.out.println("serverAddress-->>" + serverAddress);
    }

    private String intToIp(int paramInt) {
        return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."
                + (0xFF & paramInt >> 24);
    }
}